package com.xjz.job.Once;

import cn.hutool.core.collection.CollectionUtil;
import com.xjz.esdao.PostEsDao;
import com.xjz.model.dto.post.PostEsDTO;
import com.xjz.model.entity.Post;
import com.xjz.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: FullSyncPostToEs
 * Package: com.xjz.job.Once
 * Description:
 *  全量同步帖子到 es
 * @Author 许小健
 * @Create 2025/8/15 12:35
 * @Version 1.0
 */
@Component
@Slf4j
public class FullSyncPostToEs implements CommandLineRunner {
    @Resource
    private PostService postService;

    @Resource
    private PostEsDao postEsDao;
    @Override
    public void run(String... args) throws Exception {
        List<Post> postList = postService.list();
        if(CollectionUtil.isEmpty(postList)) {
            return;
        }

        List<PostEsDTO> postEsDTOList = postList.stream().map(PostEsDTO::objToDto).collect(Collectors.toList());
        final int pageSize = 500;
        int total = postEsDTOList.size();
        log.info("FullSyncPostToEs start, total {}", total);
        for (int i = 0; i < total; i++) {
            int end = Math.min(i + pageSize,total);
            log.info("sync from {} to {}", i, end);
            postEsDao.saveAll(postEsDTOList.subList(i,end));
        }

        log.info("FullSyncPostToEs end, total {}", total);
    }
}
